<?php

class SiteController extends IController
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$lans=array('EN'=>array(
							'aboutus'=>'ABOUT US',
							'product'=>'Products',
							'category'=>'Category',
							'see'=>'See More',
		),
				'ZH'=>array(
							'aboutus'=>'关于我们',
							'product'=>'最新产品',
							'category'=>'最新分类',
							'see'=>'更多',
		),
		);
		
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		$lan=$lans[$language];
		$aboutusType=Yii::app()->params[$language.'aboutusType'];
		$AboutUsOne=array_shift(array_keys($aboutusType));
		$aboutusSummary = Config::model()->findByPk( $language.strtoupper('ABOUTUS'.$AboutUsOne));
		
		$prodList=Products::model()->findAll("IndexFlag=:IndexFlag ORDER BY Sorts ASC LIMIT :LIMIT",array(
			':IndexFlag'=>1,
			':LIMIT'=>9
		));

		foreach ($prodList as $key=>&$val){
			$img="";
			for ($a=1;$a<=1;$a++)
			{
				$col="Pic".$a;
				if($val[$col] && file_exists($val[$col])){
					$img=$val[$col];
					$val->Pic1=$img;
					break;
				}
			}
		}
		$index_bottom="INDEX_BOTTOM";
		$index_bottom_value=Config::model()->findByPk($index_bottom)->ConfigValue;
		$cateGoryAry=array();
		if($index_bottom_value=='type')
		{
			$db = Yii::app()->db;
			$a=0;
			$limit=9;
			$sql = "SELECT * FROM {{category}} WHERE Flag=1 AND ParentID=0";
			$topCaregory = $db->createCommand( $sql )->queryAll();
			if(!empty($topCaregory)){
				foreach ($topCaregory as $topkey=>$topval){
					$sql = "SELECT * FROM {{category}} WHERE Flag=1 AND ParentID={$topval['ID']}";
					$Caregory = $db->createCommand( $sql )->queryAll();
					if(!empty($Caregory))
					{
						foreach ($Caregory as $Ckey=>$Cval){
							if($a<$limit)
							{
								$cateGoryAry[]=$Cval;
							}else{
								break;
							}
						}
					}
				}
			}
		}
		//var_dump($cateGoryAry);
		$string=$this->noBreakWord(strip_tags($aboutusSummary['ConfigValue']),580);
		$this->render('index' , array(
			'aboutusSummary' =>$string,
			'prodList'=>$prodList,
			'cateGoryAry'=>$cateGoryAry,
			'index_bottom_value'=>$index_bottom_value,
			'language'=>$language,
			'lan'=>$lan
		) );
	}
	
	private function   noBreakWord($string, $max){
		$testChar = substr($string, $max, 1);
		if(!$testChar)
		{
			return $string;
		}
		if ($testChar == " ") {
		  return substr($string, 0, $max);
		} else {
			 while ($testChar<>" "){
			   $testChar = substr($string, $max, 1);
			   if ($testChar == " "){
				 return substr($string, 0, $max).'...';
			   } else {
				   $max = $max-1;
				 }
			 }
		  }
  }
	
	public function actionprodlist($CaID="")
	{
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		$Category_name="PRODUCTS LIST";
		if(!empty($CaID)){
			$db = Yii::app()->db;
			$sql = "SELECT * FROM {{products}} WHERE CategoryId={$CaID} LIMIT 1";
			$product = $db->createCommand( $sql )->queryRow();
			if ( !empty( $product ) ){
				$this->redirect( $this->createUrl( 'site/Pinfo' , array('ID'=>$product['ID']) ) );
			}
			$sql = "SELECT * FROM {{category}} WHERE ID={$CaID}";
			$Category = $db->createCommand( $sql )->queryRow();
			$Category_name=$Category[$language.'Name'];
			$datas=array();
			if($Category && !$Category['ParentID'])
			{
				$sql=" SELECT * FROM {{category}} WHERE ParentID={$CaID}";
				$nextCategory = $db->createCommand( $sql )->queryAll();
				foreach ($nextCategory as $nKey=>$nVal)
				{
					$info=Products::model()->findAll("CategoryId=:CaID ORDER BY OptTime DESC",array(
						':CaID'=>$nVal['ID']
					));
					if(!empty($info))
					{
						foreach ($info as $ival)
						{
							$datas[]=$ival;
						}
					}					
				}
			}	
			//var_dump($datas);		
			$info=Products::model()->findAll("CategoryId=:CaID ORDER BY OptTime DESC",array(
				':CaID'=>$CaID
			));
			foreach ($info as $ival){
				$datas[]=$ival;
			}
			//var_dump($datas);
		}else{
			$datas=Products::model()->findAll("ID>:ID ORDER BY Sorts ASC",array(
				'ID'=>0
			));
		}
		
		foreach ($datas as $key=>&$val){
			$img="";
			for ($a=1;$a<=5;$a++)
			{
				$col="Pic".$a;
				if($val[$col] && file_exists($val[$col])){
					$img=$val[$col];
					$val->Pic1=$img;
					break;
				}
			}
		}		
		
		$this->render('prodlist' , array(
			'language'=>$language,
			'Category_name'=>$Category_name,
			'prodlist'=>$datas
		));		
	}
	
	public function actionPinfo($ID)
	{
		$ID=intval($ID);
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		
		$datas=Products::model()->findByPk($ID);
		
		if(empty($datas))
		{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		
		if($datas['CategoryId'])
		{
			$db = Yii::app()->db;
			$sql = "SELECT * FROM {{category}} WHERE ID={$datas['CategoryId']}";
			$Category = $db->createCommand( $sql )->queryRow();
			//$Categorybs=Category::model()->findByPk($datas['CategoryId']);
		}

		$nameCol=$language.'Name';
		$SummaryCol=$language.'Summary';
		$ContentCol=$language.'Content';
		$this->render('pinfo' , array(
			'language'=>$language,
			'datas'=>$datas,
			'Category'=>$Category,
			'nameCol'=>$nameCol,
			'SummaryCol'=>$SummaryCol,
			'ContentCol'=>$ContentCol,

		));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		$contactUs = Config::model()->findByPk( $language.'CONTACTUS');
		$this->render('contact',array(
			'contactUs'=>$contactUs['ConfigValue'],
			'menuTitle' => $language === 'ZH' ? '联系我们' : 'Contact us',
		));
	}

	public function actionAboutus(){
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		$aboutusType=Yii::app()->params[$language.'aboutusType'];
		$typeAry=array_keys($aboutusType);
		foreach ($aboutusType as $tKey=>$tVal){
				$array[]=$language.'ABOUTUS'.strtoupper($tKey);			
		}
		foreach ($array as $akey=>$aval){		
			$datas[$typeAry[$akey]] = Config::model()->findByPk($aval)->ConfigValue;
		}
		$this->render('about',array(
			'datas'=>$datas,
			'language'=>$language,
			'menuTitle' => $language === 'ZH' ? '关于我们' : 'Abouts us',
		));
	}
	
	public function actionFaq(){
		$language = strtoupper( Yii::app()->session->offSetGet( "FrontLanguage" ) );
		$contactUs = Config::model()->findByPk( $language.'FAQ');
		$this->render('faq',array(
			'contactUs'=>$contactUs['ConfigValue'],
			'menuTitle' => $language === 'ZH' ? '问与答' : 'FAQ',
		));
	}
		
	/**
	 * @todo 切换语言
	 * @param string $language 'zh'中文,'en'英文
	 */
	public function actionChange( $language ){
		$referUrl = isset( $_SERVER['HTTP_REFERER'] ) && !empty( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : $this->createUrl( Yii::app()->getHomeUrl() );
		$language = strtoupper( $language ) == 'ZH' ? 'ZH' : 'EN' ;
		Yii::app()->session->add( 'FrontLanguage' , $language) ;
		$this->redirect( $referUrl );
	}
	
}